package cm.android.mytodoit.view;

import cm.android.mytodoit.R;
import cm.android.mytodoit.controller.Todo_SQLOpenHelper;
import cm.android.mytodoit.model.BuyElement;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.Toast;

public class DetailBuyView extends Activity {

	private int id;
	private EditText name, quantity, where;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.detailbuyelement);

		this.id = this.getIntent().getExtras().getInt(BuyElement.TC_ID);

		this.name = (EditText) findViewById(R.id.et_detailbuy_name);
		this.quantity = (EditText) findViewById(R.id.et_detailbuy_quanty);
		this.where = (EditText) findViewById(R.id.et_detailbuy_where);
		
		
		Todo_SQLOpenHelper sqlOpenHelper = new Todo_SQLOpenHelper(this);
		
		SQLiteDatabase database = sqlOpenHelper.getReadableDatabase();
		
		Cursor cursor = database.query(BuyElement.TABLE_NAME, null,
				BuyElement.TC_ID + " = "+id,
				null,
				null,
				null,
				null);
		
		while (cursor.moveToNext()) {
			this.name.setText(cursor.getString(cursor.getColumnIndex(BuyElement.TC_NAME)));
			this.quantity.setText(cursor.getString(cursor.getColumnIndex(BuyElement.TC_QUANTITY)));
			this.where.setText(cursor.getString(cursor.getColumnIndex(BuyElement.TC_INFO)));
		}

		cursor.close();
		database.close();
	}

	public void onButtonClick(View view) {

		Todo_SQLOpenHelper sqlOpenHelper = new Todo_SQLOpenHelper(this);

		SQLiteDatabase database = sqlOpenHelper.getWritableDatabase();

		switch (view.getId()) {

		case R.id.bu_detailbuy_saveButton:

			try {

				ContentValues values = new ContentValues();

				values.put(BuyElement.TC_INFO, where.getText().toString());
				values.put(BuyElement.TC_PRIORITY, quantity.getText()
						.toString());
				values.put(BuyElement.TC_NAME, name.getText().toString());

				database.update(BuyElement.TABLE_NAME, values, BuyElement.TC_ID
						+ " = " + this.id, null);
				
			} catch (Exception e) {
				Toast.makeText(this, "update failed", Toast.LENGTH_SHORT)
				.show();
			}

			break;

		case R.id.bu_detailbuy_delete:

			try {

				database.delete(BuyElement.TABLE_NAME, BuyElement.TC_ID + " = "
						+ this.id, null);
			} catch (Exception e) {
				Toast.makeText(this, "delete failed", Toast.LENGTH_SHORT)
						.show();
			}

			break;
		}

		database.close();
		this.finish();

	}
}
